﻿using System;
using System.Collections.Generic;
using System.Text;
using Atmk.WaterMeter.MIS.Commons.Enums;

namespace Atmk.WaterMeter.MIS.Commons.Utils
{
    public class DateTimeHelper
    {
        /// <summary>
        /// 获取指定时间所在的指定期间的起止日期
        /// </summary>
        /// <param name="period">期间类型</param>
        /// <param name="beginDate">开始日期</param>
        /// <param name="endDate">结束日期</param>
        /// <param name="dateTime">指定时间</param>
        public static void GetPeriod(Period period, out DateTime beginDate, out DateTime endDate,DateTime? dateTime=null)
        {
            var date = dateTime ?? DateTime.Now;
            var year = date.Date.Year;
            var month = date.Date.Month;
            // ReSharper disable once SwitchStatementMissingSomeCases
            switch (period)
            {
                case Period.Year: //年
                    beginDate = new DateTime(year, 1, 1);
                    endDate = new DateTime(year, 12, 31);
                    break;
                case Period.Quarter://季度
                    beginDate = new DateTime(year, month,1).AddMonths(0 - (month - 1) % 3);
                    endDate = beginDate.AddMonths(3).AddMilliseconds(-1);
                    break;
                case Period.Month: //月
                    beginDate = new DateTime(year, month, 1);
                    endDate = beginDate.AddMonths(1).AddDays(-1);
                    break;
                case Period.Week: //周
                    var week = (int)DateTime.Today.DayOfWeek;
                    if (week == 0) week = 7; //周日
                    beginDate = date.AddDays(-(week - 1));
                    endDate = beginDate.AddDays(6);
                    break;
                default: //日
                    beginDate = date.Date;
                    endDate = date.Date.AddDays(1).AddMilliseconds(-1);
                    break;
            }
        }

        /// <summary>
        /// 获取指定时间的上N个季度或下N个季度的月初
        /// </summary>
        /// <param name="quarter">季度数,正数</param>
        /// <param name="nextQuarter">是否下个季度，否则获取上{quarter}个季度</param>
        /// <param name="dateTime"></param>
        public static DateTime GetQuarter(int quarter,bool nextQuarter, DateTime? dateTime = null)
        {
            var date = dateTime ?? DateTime.Now;
            var year = date.Date.Year;
            var month = date.Date.Month;
            if (!nextQuarter)
                quarter = -quarter;
            return new DateTime(year, month, 1).AddMonths(quarter*3 - (month - 1) % 3);
        }
        /// <summary>
        /// 获取指定实际季度的月初
        /// </summary>
        /// <param name="dateTime"></param>
        public static DateTime GetQuarter(DateTime? dateTime = null)
        {
            var date = dateTime ?? DateTime.Now;
            var year = date.Date.Year;
            var month = date.Date.Month;
            return new DateTime(year, month, 1).AddMonths(0 - (month - 1) % 3);
        }
    }
}
